package sw6.girafplaceclient;

import java.util.ArrayList;
import java.util.List;

import girafPlace.lib.*;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * Handles the presentation of applications that are installed on 
 * the device, and are relevant to the user, according to the current UserProfile.
 * @author SW6C
 */
public class ApplicationAdapter extends BaseAdapter {
	protected List<Application> apps = new ArrayList<Application>();
	protected static Context mContext;
	protected static String tag = "GirafPlaceClient";
	/**
	 * Gets a list of applications that are relevant to the user.
	 * @return The applications relevant to the user.
	 */
	public List<Application> getApps() {
		return apps;
	}

	/**
	 * Sets a list of applications that are relevant to the user.
	 * @param apps The applications to set that are relevant to the user.
	 */
	public void setApps(List<Application> apps) {
		this.apps = apps;
		this.notifyDataSetChanged();
	}

	private static ApplicationAdapter instance = null;
	
	private ApplicationAdapter() {/**Exists only to defeat instantiation.*/}
	
	/**
	 * Gets the running instance of the ApplicationAdapter. 
	 * If no instance exist, an instance is created and returned.
	 * NOTE: This is a singleton.
	 * @param context The context, to get a instance of the ApplicationAdapter.
	 * @return The running instance.
	 */
	public static ApplicationAdapter getInstance(Context context) {
		mContext = context;
		if(instance == null) {
			Log.d(tag,"Creating the first instance and executing the network task.");
			instance = new ApplicationAdapter();
			new NetworkTask(mContext).execute();
		}
		return instance;
	}
	
	/** Gets the number of applications that are installed and shown. */
	@Override
	public int getCount() {
		return apps.size();
	}
	
	/** Gets the specified application, in the list. */
	@Override
	public Object getItem(int position) {
		return apps.get(position);
	}
	
	/**
	 * Returns the first available applicationId, of the application 
	 * that are relevant to the user.
	 * NOTE: This is NOT used, but has to exist.
	 */
	@Override
	public long getItemId(int position) {
		return 0;
	}
	
	/**
	 * Gets a view at the specified position in the specified data set.
	 * @param position The position of the application.
	 * @param convertView Either null, or no longer used icon for recycling.
	 * @param parent The ViewGroup of the parent.
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AppView appView;
        if (convertView == null) {//if convertView is not recycled, initialize some attributes
            appView = new AppView(mContext,apps.get(position));        
        } else {
            appView = (AppView) convertView;
        }
        
        appView.setApp(apps.get(position));
        
        return appView;
	}
}